package com.ycl.javacore.algorithm;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * User: OF1089 杨成龙
 * Date: 2019/8/14
 * Time: 2:23 PM
 * Desc: 二叉树的层序遍历
 */
public class AlgoCast33Tree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    /**
     * 层序遍历，将每一层的每个
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrderTraversal(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> result = new ArrayList<>();
        Queue<TreeNode> q = new LinkedList<>();
        q.add(root);
        while (!q.isEmpty()) {
            int size = q.size();
            List<Integer> elems = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = q.poll();
                elems.add(node.val);
                if (node.left != null) {
                    q.add(node.left);
                }
                if (node.right != null) {
                    q.add(node.right);
                }
            }
            result.add(elems);
        }
        return result;
    }

}
